package com.yzs.base.view;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 给 EditText 添加拦截，监听输入，限制输入
 *      binding.etContent.filters = arrayOf<InputFilter>(MaxLengthEditTextFilter(10), CharFilter.wnrCharFilter())
 *
 */
public class MaxLengthEditTextFilter implements InputFilter {

    private final int mMax;

    public MaxLengthEditTextFilter(int mMax) {
        this.mMax = mMax;
    }

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int keep = mMax - (dest.length() - (dend - dstart));
        if (keep <= 0) {
            if (mListener != null) mListener.onFilter(mMax);
            return "";
        } else if (keep >= end - start) {
            return null; // keep original
        } else {
            keep += start;
            if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                --keep;
                if (keep == start) {
                    return "";
                }
            }
            return source.subSequence(start, keep);
        }
    }

    public int getMax() {
        return mMax;
    }

    public interface OnInputFilterListener {
        void onFilter(int maxLength);
    }

    private OnInputFilterListener mListener;

    public void setListener(OnInputFilterListener listener) {
        this.mListener = listener;
    }
}